//
//  BHCommonTool.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/24.
//

import UIKit
import Photos

class BHCommonTool {
    // 拍照或相册使用
    var canEdite: Bool = false
    // 截屏
    var screenShotResultBlock:((Bool,String) -> Void)?
    
    
    
    // 系统alert
    static func showAlertWith(showVC: UIViewController?, title: String?, message: String?, okBtn: String, cancel: String?, okBlock: @escaping (Bool) -> Void ) {
        
        let alert = UIAlertController.init(title: title, message: message, preferredStyle: .alert)
        
        let actSheetTake = UIAlertAction.init(title: okBtn, style: .default) { (action) in
            okBlock(true)
        }
        alert.addAction(actSheetTake)
        if cancel != nil {
            let cancelAct = UIAlertAction.init(title: cancel, style: .cancel) { (action) in
                okBlock(false)
            }
            alert.addAction(cancelAct)
        }
        if showVC == nil {
            BHBaseViewController.currentViewController?.present(alert, animated: true, completion: nil)
        }else {
            showVC!.present(alert, animated: true)
        }
    }
    
    // 自定义按钮
    static func showCustomAlertWith(showVC: UIViewController?, title: String?, message: String?, okBtn: String, cancel: String?, okBlock: @escaping (Bool) -> Void ) {
        var view: BHAlertView?
        if showVC != nil {
            view = showVC!.view.viewWithTag(999) as? BHAlertView
        }else {
            view = UIWindow.keyWindow.viewWithTag(999) as? BHAlertView
        }
        
        if view == nil {
            view = BHAlertView.loadFromXib()
            view?.tag = 999
            if showVC != nil {
                showVC?.view.addSubview(view!)
            }else {
                UIWindow.keyWindow.addSubview(view!)
            }
        }
        view?.title_label.text = title
        let att = message?.toAttribute()
        let style = NSMutableParagraphStyle.init()
        style.alignment = .center
        style.lineSpacing = 5
        att?.addAttributes([NSMutableAttributedString.Key.paragraphStyle:style], range: NSRange(location: 0, length: message?.count ?? 0))
        att?.addAttributes([NSMutableAttributedString.Key.foregroundColor:UIColor.color_999999], range: NSRange(location: 0, length: message?.count ?? 0))

        view?.text_textView.attributedText = att
        view?.cancelBtn.setTitle(cancel, for: .normal)
        view?.confirmBtn.setTitle(okBtn, for: .normal)
        view?.show()
        
        view?.confirmActBlock = {
            okBlock(true)
        }
        
        view?.cancelActBlock = {
            okBlock(false)
        }
    }
    
    static func showSheetWith(showVC: UIViewController?,title: String?, messages: [String], handler: @escaping (Int) -> Void) {
        let alert = UIAlertController.init(title: title, message: nil, preferredStyle: .actionSheet)
        
        for (index, text) in messages.enumerated() {
            
            let sheet = UIAlertAction.init(title: text, style: .default) { (action) in
                handler(index)
            }
            sheet.setValue(UIColor.color_34CE98, forKey: "titleTextColor")
            alert.addAction(sheet)
        }
        let cancel = UIAlertAction.init(title: "取消", style: .cancel) { (action) in
            handler(-1)
        }
        cancel.setValue(UIColor.color_34CE98, forKey: "titleTextColor")
        alert.addAction(cancel)
        DispatchQueue.main.async {
            if showVC == nil {
                BHBaseViewController.currentViewController?.present(alert, animated: true, completion: nil)
            }else {
                showVC!.present(alert, animated: true)
            }
        }
    }
}
// 截屏
extension BHCommonTool {
    func screenShotRect(view: UIView, block: ((Bool,String) -> Void)?) {
        self.screenShotResultBlock = block
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let imageRet = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        UIImageWriteToSavedPhotosAlbum(imageRet, self, #selector(saveImage(image:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    @objc func saveImage(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
           if error != nil{
            self.screenShotResultBlock?(false,"截屏失败")
              
           }else{
            self.screenShotResultBlock?(true,"截屏失败")
           }
    
    }
}

extension BHCommonTool {
    // 拍照
    private static func takePhotoAct(canEdite: Bool, finishBlock: @escaping (UIImage?) -> Void) {
        let picker = BHImagePickManager.shareInstance
        picker.allowsEditing = canEdite
        picker.takeCamera { (img) in
            finishBlock(img)
        }
    }
    
    // 选择照片
    private static func photoChoseAct(canEdite: Bool,maxCount count: Int, completeHandler finish: @escaping (UIImage?,PHAsset?) -> Void) {
        let picker = BHImagePickManager.shareInstance
        picker.allowsEditing = canEdite
        picker.selectPhoto { (img,asset) in
            finish(img,asset)
        }
    }
    
    
}

extension BHCommonTool {
    
    // 拍照,外界调用
    func takePhoto(completeHandler: @escaping (UIImage?) -> Void) {
        BHImagePickManager.permissionForCamera { (authStatus) in
            if authStatus == .authorized {
                BHCommonTool.takePhotoAct(canEdite: self.canEdite) { (img) in
                    completeHandler(img)
                }
            }else {
                completeHandler(nil)
            }
        }
    }
    
    func photeChose(maxCount: Int, completeHandler: @escaping (UIImage?,PHAsset?) -> Void) {
        BHImagePickManager.permissionForAlbum { (status) in
            if status == .authorized {
                BHCommonTool.photoChoseAct(canEdite: self.canEdite, maxCount: maxCount) { (img,asset) in
                    completeHandler(img,asset)
                }
            }else {
                completeHandler(nil,nil)
            }
        }
    }
    
    
    // 打电话
    static func telAct(_ mobile: String, completeHandler: @escaping (Bool) -> Void) {
        if mobile.isEmpty == true {
            completeHandler(false)
        }else {
            if UIApplication.shared.canOpenURL(URL.init(string: "tel://"+mobile)!) == true {
                DispatchQueue.main.async {
                    UIApplication.shared.open(URL.init(string: "tel://"+mobile)!, options: [:]) { (success) in
                        completeHandler(success)
                    }
                }
                
            }else {
                completeHandler(false)
            }
        }
    }
    
    
    func tempDownload(url: String, block: @escaping (String) -> Void)  {
        let session = URLSession.shared
        let url: URL = URL.init(string: url)!
        
        let task = session.downloadTask(with: url) { (downloadUrl, response, error) in
            var localPath: String = ""
            if error != nil {
                let locationUrl = NSTemporaryDirectory()+url.lastPathComponent
                let manager = FileManager.default
                try! manager.moveItem(atPath: downloadUrl!.path, toPath: locationUrl)
               
                localPath = locationUrl
            }
            block(localPath)
        }
        task.resume()
        
    }
}


extension BHCommonTool {
    static func permisstionAlertShow(_ forCamera: Bool) {
        var alertMessage: String = "您未允许我们访问您的相机，请稍后在\n设置->隐私->相机\n打开访问开关"
        if forCamera == false {
            alertMessage = "您未允许我们访问您的相册，请稍后在\n设置->隐私->照片\n打开访问开关"
        }
        let alert = UIAlertController.init(title: nil, message: alertMessage, preferredStyle: .alert)

        let cancelAct = UIAlertAction.init(title: "好的", style: .cancel, handler: nil)
        alert.addAction(cancelAct)
        BHNavigationController.currentNavigationController?.present(alert, animated: true)
    }
    
    // 拍照的使用
    static func showPicAlert(showVC: UIViewController, takeBlock: @escaping (Int) -> Void) {
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
 
        let actSheetTake = UIAlertAction.init(title: "拍照", style: .default) { (action) in
            takeBlock(0)
        }
        let actSheetChose = UIAlertAction.init(title: "相册选择", style: .default) { (action) in
            takeBlock(1)
        }
        alert.addAction(actSheetTake)
        alert.addAction(actSheetChose)

        let cancelAct = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        alert.addAction(cancelAct)
        showVC.present(alert, animated: true)
    }
}

// 根据视频url获取首帧图片
extension BHCommonTool {
    static func thumbImage(url: String) -> UIImage? {
        let asset = AVURLAsset.init(url: URL.init(string: url)!, options: nil)
        let gen = AVAssetImageGenerator.init(asset: asset)
        gen.appliesPreferredTrackTransform = true
        let time = CMTimeMakeWithSeconds(0, preferredTimescale: 1)
        var actualTime : CMTime = CMTimeMakeWithSeconds(0, preferredTimescale: 0)
        do {
            let image = try gen.copyCGImage(at: time, actualTime: &actualTime)
             return UIImage.init(cgImage: image)
        } catch  {
            return nil
        }
    }
}

// 应用信息部分
extension BHCommonTool {
    static var appVersion: String {
        get {
            let infoDictionary = Bundle.main.infoDictionary!
            let version = infoDictionary["CFBundleShortVersionString"] as! String
            return version
        }
    }
}
